package com.wuxinwudai.android.widget;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * ContactsAdapter 类为通讯录接口适配器类
 * @author 吾心无待
 */
public class ContactsAdapter extends CursorAdapter{
	private ContentResolver content;
	/**
     * 要获取通讯录的字段
	 */
	public static final String[] PEOPLE_PROJECTION = new String[]{
		Contacts.People._ID,Contacts.People.PRIMARY_PHONE_ID,
		Contacts.People.TYPE,Contacts.People.NUMBER,
		Contacts.People.LABEL,Contacts.People.NAME
	};

	/**
	 * 构造函数，初始化 ContactsAdapter 类的一个新实例
	 * @param context 上下文对象
	 * @param cursor 查询光标
     */
	public ContactsAdapter(Context context,Cursor cursor){
		super(context,cursor);
		content = context.getContentResolver();
	}

	@Override
	public void bindView(View view,Context context,Cursor cursor){
		((TextView)view).setText(cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME)));
	}

	@Override
	public View newView(Context context,Cursor cursor,ViewGroup parent){
		final LayoutInflater inflater = LayoutInflater.from(context);
		final TextView view = (TextView)inflater.inflate(android.R.layout.simple_dropdown_item_1line,parent,false);
		view.setText(cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME)));
		return view;
	}

	@Override
	public String convertToString(Cursor cursor){
		return cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME));
	}

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		if(getFilterQueryProvider() != null){
			return super.runQueryOnBackgroundThread(constraint);
		}
		StringBuilder buffer = null;
		String[] args = null;
		if(constraint != null){
			buffer = new StringBuilder();
			buffer.append("UPPER(");
			buffer.append(Contacts.ContactMethods.NAME);
			buffer.append(") GLOB ?");
			args = new String[]{
					constraint.toString().toUpperCase() + "*"
			};
			return content.query(Contacts.People.CONTENT_URI,
					PEOPLE_PROJECTION, buffer == null?null:buffer.toString(),
					args, Contacts.People.DEFAULT_SORT_ORDER);
		}
		return null;
	}

}





























